<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Cart extends Controller_User_Template{

	public function action_index()
	{
		$id = Cookie::get('items');
		$items = explode(',', $id);
		$items = DB::select('item_id')->from('inventory_items')
				->where('id', 'in', $items)
				->execute();
		$itemlist = array();
		foreach ($items as $item):
			echo $item['item_id'];
			$itemlist[] = ORM::factory('item')
					->where('id', '=', $item['item_id'])
					->find();
		endforeach;	
		
		$this->template->content = $itemlist;
		$view = new View('cart/index');
		$view->set("items", $itemlist);
		$this->template->content = $view;
		
		if($loggedin = Auth::instance()->get_user())
		{
			$user_id = $loggedin->id;
			$items = DB::select()->from('cart')->join('items')
					->on('cart.item_id', '=', 'items.id')
					->where('user_id', '=' , $user_id)
					->execute();
			
			$view = new View('cart/index');
			$view->set("items", $items);
			$this->response->body($view);
		}
		else
		{
			$view = new View('user/login');
			$this->response->body($view);
		}			
	}
	
	public function action_add()
	{
		
		$item_id = $this->request->post('item');
		$item = ORM::factory('item', $item_id);
		
		$attributes = $item->item_attributes->find_all();
		
		echo count($attributes).' rows';
		
		if(count($attributes)):		
			$inv_items = $item->inventory_items->find_all();

			foreach($inv_items as $inv_item):
				$found = true;
				foreach($inv_item->attributes->find_all() as $attr):
					if($_POST['attr'.$attr->attribute_id] !== $attr->value_id) {
						$found = false;
					}
				endforeach;
				if($found) {
					$inv_item_id = $inv_item->id;	
					break;
				}
			endforeach;
		else:
			$inv_item = $item->inventory_items->find();
			$inv_item_id = $inv_item->id;
		endif;
		
		if($list = Cookie::get('items'))
		{
			$amount = Cookie::get('amounts');
			
			$list = $list.', '.$inv_item_id;
			Cookie::set('items', $list);
			
			$amount = $amount.', 1'; 
			Cookie::set('amounts', $amount);
			$this->request->redirect('cart/index');
		}
		else
		{
			Cookie::set('items', $inv_item_id );
			Cookie::set('amounts', '1');
			$this->request->redirect('cart/index');
		}	
	}
	
	public function action_remove()
	{
		$cart_id = $this->request->param('id');
		$id = Cookie::get('items');
		$amount = Cookie::get('amounts');
		$items = explode(',', $id);
		unset($items[$cart_id]);
		$items = implode(',', $items);
		
		$amounts = explode(',', $amount);
		unset($amounts[$cart_id]);
		$amounts = implode(',', $amounts);
		
		Cookie::set('items', $items);
		Cookie::set('amounts', $amounts);
		$this->request->redirect('cart/index');

	}
	
	public function action_payment()
	{
		if($loggedin = Auth::instance()->get_user())
		{		
			$userid = $loggedin->id;
			$address = DB::select()->from('addresses')
						->where('user_id', '=', $userid)
						->execute();
			
			$items = Cookie::get('items');
			$amount = Cookie::get('amounts');	
			$total = $this->request->post('total');
			
			$view = new View('cart/payment');
			
			$view->set('order', explode(',', $items));
			$view->set('total', $total);
			$view->set('address', $address);
			$view->set('values', '');
			$view->set('errors', '');
			
			$this->template->content = $view;
		}
		else
		{
			$view = new View('user/login');
			$this->template->content = $view;
		}
	}
	
	public function action_placeorder()
	{
		$loggedin = Auth::instance()->get_user();
		$userid = $loggedin->id;
		
		$items = explode(',', Cookie::get('items'));
		$amounts = explode(',', Cookie::get('amounts'));
		$errors;

		$instock = true;
		$i = 0;
		while($i < count($items)) {
			$inv_item = ORM::factory('inventoryItem', $items[$i]);
			$quantity = $amounts[$i];
			
			if($quantity > $inv_item->quantity) {
				$instock = false;
				$errors['notinstock'] = 'true';
				break;
			}
			
			$i += 1;
		}
		
		if($instock) {
			$total = $this->request->post('total');
			$date_placed = date("j, n, Y");
			
			try {	
				$order = new Model_Order();
				$order->values($_POST);
				$order->user_id = $userid;
				$order->save();	
				$orderid = $order->id;
		
				$transaction = new Model_Transaction();
				$transaction->values($_POST);
				$transaction->user_id = $userid;
				$transaction->order_id = $orderid;
				$transaction->date_created = strtotime('now');
				
				$shipping_days = 0;
				if(isset($_POST['shipping_method'])) {
					$shipping_method_str = $this->request->post('shipping_method');
					if($shipping_method_str == 'Overnight') {
						$shipping_days = 1;	
					}
					else if($shipping_method_str == 'Three Day') {
						$shipping_days = 3;	
					}
					else if($shipping_method_str == 'Five Day') {
						$shipping_days = 5;	
					}
					else {}
				}
				
				$transaction->date_finalized = strtotime('+ '.$shipping_days.' days');
				$transaction->save();
				
				$index = 0;
				foreach($items as $item):
					DB::insert('orderitems', array('order_id', 'item_id', 'quantity'))
						->values(array($orderid, $item, $amounts[$index]))
						->execute();
					$inv_item = ORM::factory('orderitem', $item);
					$inv_item->quantity = $inv_item->quantity - $amounts[$index];
					$inv_item->save();
					$index++;
				endforeach;
			}
			catch(ORM_Validation_Exception $e) {
				$errors = $e->errors();
			}
		}
		
		if(! empty($errors) ) {
			// errors found
			$values = $this->request->post();
			$total = $_POST['amount'];
			$address = DB::select()->from('addresses')
						->where('user_id', '=', $userid)
						->execute();
			$view = View::factory('cart/payment');
			$view->set('values', $values);
			$view->set('total', $total);
			$view->set('address', $address);
			$view->set('errors', $errors);
			
			$this->template->content = $view;	
				
		}
		else {
			// no errors
			Cookie::delete('items');
			Cookie::delete('amounts');
	  
			$view = new View('cart/index');
			$view->set('order', $order);
			$view->set('total', $total);
			
			$this->template->content = $view;	
			$this->request->redirect('user/profile/orders');
		}
		
	}
	
	public function action_quantity()
	{
		$item_id = $_GET['index'];
		$quantity = $_GET['quantity'];
		
		$amounts = Cookie::get('amounts');
		$quantarray = explode(',', $amounts);
		$quantarray[$item_id] = $quantity;
		$amounts = implode(',', $quantarray);
		
		Cookie::set('amounts', $amounts);
		$this->request->redirect('cart/index');
	}
}